﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using CoreLibrary.Repo;
using Entities.DataBase.Obj;
using Entities.DataBase.Persistent;

namespace Entities.DataBase.Impl {

    public class CostRepository : BaseRepository<Cost>, ICostRepository {

        private static readonly Func<DataContext, string, Cost>
          LinqGetCostById = CompiledQuery.Compile((DataContext context, string id)
              => context.GetTable<Cost>().SingleOrDefault(o => o.Id.Equals(id)));

        private static readonly Func<DataContext,IQueryable<Cost>>
          LinqGetCosts = CompiledQuery.Compile((DataContext context)
              => context.GetTable<Cost>());

        public override string TableName {
            get {
                return "D_COST";
            }
        }

        public void Add(Cost cost) {
            Execute((context, ts) => {
                var costByID = LinqGetCostById(context, cost.Id);
                if (costByID != null) {
                    throw new Exception("Cost already exist.");
                }

                context.GetTable<Cost>().InsertOnSubmit(cost);
                context.SubmitChanges();
                ts.Complete();
            });
        }

        public List<Cost> List() {
            return Execute(context => LinqGetCosts(context).ToList());
        }

        public Cost Get(string costId) {
            return Execute(context => LinqGetCostById(context, costId));
        }

        public void Update(string costId, CostUpdator updator) {
            Execute((context, ts) => {
                var cost = LinqGetCostById(context, costId);
                if (cost == null) {
                    throw new Exception("Cost doesn't exist.");
                }

                updator.UpdateCost(cost);
                context.SubmitChanges();
                ts.Complete();
            });
        }

        public void Remove(string costId) {
            Execute((context, ts) => {
                var cost = LinqGetCostById(context,costId);
                if (cost == null) {
                    throw new Exception("Cost doesn't exist.");
                }

                context.GetTable<Cost>().DeleteOnSubmit(cost);
                context.SubmitChanges();
                ts.Complete();
            });
        }

    }
}